package sg.edu.nus.iss.club;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BookingRegister {
	
	private Map<Facility, List<Booking>> bookings;
	
	public BookingRegister() {
		bookings = new HashMap<Facility, List<Booking>>();
	}
	
	public void addBooking(Member member, Facility facility, Date startDate, Date endDate) throws BadBookingException {
		Booking newBooking = new Booking(member, facility, startDate, endDate);
		List<Booking> bookingList = bookings.get(facility);
		if (bookingList != null) {
			for (Booking aBooking : bookingList) {
				if (aBooking.overlaps(newBooking)) {
					throw new BadBookingException("Encounters overlaps when booking.");
				}
			}
			bookingList.add(newBooking);
		} else {
			bookingList = new ArrayList<Booking>();
			bookingList.add(newBooking);
			bookings.put(facility, bookingList);
		}
	}
	
	public List<Booking> getBookings(Facility facility, Date startDate, Date endDate) {
		List<Booking> resultList = new ArrayList<Booking>();
		List<Booking> bookingList = bookings.get(facility);
		if (bookingList != null) {
			for (Booking aBooking : bookingList) {
				if (aBooking.overlaps(startDate, endDate)) {
					resultList.add(aBooking);
				}
			}
		} else {
			//do nothing
		}
		return resultList;
	}
	
	public void removeBooking(Booking booking) {
		List<Booking> bookingList = bookings.get(booking.getFacility());
		Booking removeBookingItem = null;
		if (bookingList != null) {
			for (Booking aBooking : bookingList) {
				if (aBooking.getMember().getMemberNumber() == booking.getMember().getMemberNumber() &&
					aBooking.getStartDate().equals(booking.getStartDate()) &&
					aBooking.getEndDate().equals(booking.getEndDate())) {
					removeBookingItem = aBooking;
				}
			}
			bookingList.remove(removeBookingItem);
		}
	}
	
}
